<template>
	<div class="app-container">
		<div class="header">
			<svg-icon icon-class="system-erp" style="width: 18px; height: 18px; position: relative; top: 1px; margin-right: 10px" />修改采购信息
		</div>
		<el-form ref="baseform" :model="form" label-position="right" :rules="rules" label-width="50px">
			<el-form-item prop="procureName" label="名称">
				<el-input :disabled="userStore.$state.roles.includes('cg1')" v-model="form.procureName" style="width: 50%" placeholder="请输入名称" />
			</el-form-item>
			<el-form-item prop="projectId" label="项目">
				<el-select
					v-model="form.projectId"
					style="width: 50%"
					filterable
					:disabled="userStore.$state.roles.includes('cg1')"
					remote
					reserve-keyword
					remote-show-suffix
					placeholder="请选择项目"
					:remote-method="remoteMethod"
					:loading="loading">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
		</el-form>
		<el-form-item label="附件上传">
			<el-upload
				v-model:file-list="filelist"
				:disabled="userStore.$state.roles.includes('cg1')"
				:action="fileUrl"
				ref="upload"
				:headers="token"
				name="files"
				:on-success="handleSuccess"
				:on-remove="handleRemove"
				style="width: 640px">
				<el-button type="primary">上传</el-button>
			</el-upload>
		</el-form-item>
		<el-divider style="margin: 15px 0" />
		采购项配置
		<el-divider style="margin: 15px 0" />
		<el-button type="warning" v-if="!userStore.$state.roles.includes('cg1')" @click="addItem">新增规格</el-button>
		<el-button type="warning" v-if="!userStore.$state.roles.includes('cg1')" @click="importProduct">导入</el-button>
		<div style="overflow-x: auto; height: 250px; overflow-y: auto">
			<div class="item-row" v-for="(item, index) in form.projectProcureItemBos" :key="index">
				<div class="item-col">
					分类：
					<el-select
						:disabled="userStore.$state.roles.includes('cg1')"
						v-model="item.itemType"
						style="width: calc(100% - 100px)"
						placeholder="请选择">
						<el-option v-for="item in item_type" :key="item.value" :label="item.label" :value="Number(item.value)" />
					</el-select>
				</div>
				<div style="width: 300px !important">
					报价单：
					<el-select
						:disabled="userStore.$state.roles.includes('cg1')"
						v-model="item.quotationItemId"
						style="width: calc(100% - 100px)"
						placeholder="请选择">
						<el-option v-for="item in quotationList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>

				<div style="width: 300px !important">
					产品分类：
					<el-select
						:disabled="userStore.$state.roles.includes('cg1')"
						v-model="item.productTypeId"
						style="width: calc(100% - 100px)"
						placeholder="请选择">
						<el-option v-for="item in productOption" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
					<!-- <el-cascader v-model="form.productTypeId" :options="productOption" style="width: calc(100% - 100px)" :show-all-levels="false" placeholder="请选择" /> -->
				</div>
				<div class="item-col">
					物品名称：
					<el-input :disabled="userStore.$state.roles.includes('cg1')" v-model="item.itemName" style="width: calc(100% - 100px)" placeholder="" />
				</div>
				<div class="item-col">
					型号规格：
					<el-input
						:disabled="userStore.$state.roles.includes('cg1')"
						v-model="item.itemParameter"
						style="width: calc(100% - 100px)"
						placeholder="" />
				</div>
				<div class="item-col">
					品牌：
					<el-input :disabled="userStore.$state.roles.includes('cg1')" v-model="item.itemBrand" style="width: calc(100% - 60px)" placeholder="" />
				</div>

				<div class="item-col">
					数量：
					<el-input-number
						:controls="false"
						v-model="item.itemNumber"
						style="width: calc(100% - 60px)"
						placeholder=""
						:precision="2"
						:step="0.01"
						@blur="notZ(item)" />
				</div>
				<div class="item-col">
					单价：
					<el-input-number
						:controls="false"
						v-model="item.itemUnitPrice"
						style="width: calc(100% - 80px)"
						placeholder=""
						:precision="2"
						:step="0.01"
						:min="0" />元
				</div>
				<div style="width: 300px">
					到货时间：
					<el-date-picker
						clearable
						:disabled="userStore.$state.roles.includes('cg1')"
						v-model="item.itemArrivalTime"
						style="width: calc(100% - 100px)"
						value-format="YYYY-MM-DD"
						type="date"></el-date-picker>
				</div>
				<div style="flex: 1">
					<el-button v-if="form.projectProcureItemBos.length > 1" type="primary" link @click="deleteRow(index)">删除</el-button>
				</div>
			</div>
		</div>
		<!-- 用户导入对话框 -->
		<el-dialog title="产品导入" v-model="open" width="400px" append-to-body>
			<el-upload
				ref="uploadRef"
				:limit="1"
				accept=".xlsx,.xls"
				:headers="token"
				:action="url + '?updateSupport=0'"
				:on-progress="handleFileUploadProgress"
				:on-success="handleFileSuccess"
				:auto-upload="false"
				drag>
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<template #tip>
					<div class="el-upload__tip text-center">
						<span>仅允许导入xls、xlsx格式文件。</span>
						<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downloadfile">下载模板</el-link>
					</div>
					<div class="el-upload__tip text-center">
						<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downloadfilePro"
							>下载产品分类对照表</el-link
						>
					</div>
				</template>
			</el-upload>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFileForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<div style="line-height: 80px; height: 80px; padding-left: 100px">
			<el-button type="primary" @click="submit">提交</el-button>
			<el-button @click="reback">返回</el-button>
		</div>
	</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
const { proxy } = getCurrentInstance()
import { selectProject } from '@/api/project/project'
import { updateProcure, getProcure, getQuotation, getProduct } from '@/api/buy/buy'
import { getToken } from '@/utils/auth'
import { download } from '@/utils/request'
import { getConfigKey } from '@/api/system/config'
const fileUrl = ref('')
getConfigKey('file_upload').then((response) => {
	fileUrl.value = response.msg
})
const token = { Authorization: 'Bearer ' + getToken() }

const filelist = ref([])
const { item_type } = proxy.useDict('item_type')
const router = useRouter()
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const baseform = ref()
const productOption = ref([])
getProduct().then((res) => {
	if (res) productOption.value = filtList(res)
})
const filtList = (data) => {
	let newData = []
	for (let item of data) {
		let obj = { label: `[${item.categoryName}]-${item.typeName}`, value: item.typeId }
		// if (item.productTypeVoList) {
		// 	let data2 = []
		// 	for (let item2 of item.productTypeVoList) {
		// 		data2.push({ label: item2.typeName, value: item2.typeId })
		// 	}
		// 	obj.children = data2
		// }
		newData.push(obj)
	}
	return newData
}
import { useRoute } from 'vue-router'
const route = useRoute()
import useTagsViewStore from '@/store/modules/tagsView'
const tagsView = useTagsViewStore()
if (route.query.id) {
	getProcure(route.query.id).then((res) => {
		for (let item in form) {
			form[item] = res.data[item]
		}
		if (res.data['procureStatus'] == '3') {
			form.procureStatus = '1'
		}
		form.auditNote = ' '
		if (res.data.fileUrl) {
			filelist.value = [{ name: res.data.fileUrl, url: res.data.fileUrl }]
		}
	})
}
const handleSuccess = (response) => {
	form.fileUrl = response.data[0]
	filelist.value = [{ name: response.data[0], url: response.data[0] }]
}
const handleRemove = () => {
	form.fileUrl = ''
}
const notZ = (item) => {
	if (item.itemNumber == 0) {
		item.itemNumber = 1
	}
}

const url = ref('')
url.value = import.meta.env.VITE_APP_BASE_API + '/function/procureItem/importData'
const open = ref(false)
/** 下载模板操作 */
function importTemplate() {
	proxy.download('/function/procureItem/export/template', {}, `user_template_${new Date().getTime()}.xlsx`)
}
const isUploading = ref(false)
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
	isUploading.value = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
	open.value = false
	isUploading.value = false
	proxy.$refs['uploadRef'].handleRemove(file)
	proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
		dangerouslyUseHTMLString: true
	})
	form.projectProcureItemBos.push(
		...response.data.map((e) => {
			e.itemNumber = Number(e.itemNumber)
			e.itemUnitPrice = Number(e.itemUnitPrice)
			return e
		})
	)
}
const downloadfile = () => {
	download({ url: '采购项导入模板.xlsx' }).then()
}
const downloadfilePro = () => {
	proxy.download('/function/product/classification', {}, `分类对照表.xlsx`)
}
/** 提交上传文件 */
function submitFileForm() {
	proxy.$refs['uploadRef'].submit()
}
const cancel = () => {
	open.value = false
}
const importProduct = () => {
	open.value = true
}
const form = reactive({
	procureId: '',
	procureName: '',
	procureStatus: '',
	projectId: '',
	fileUrl: '',
	auditNote: ' ',
	projectProcureItemBos: [
		{
			itemName: '',
			itemParameter: '',
			itemBrand: '',
			itemNumber: 1,
			itemUnitPrice: 0,
			itemArrivalTime: undefined,
			itemType: undefined,
			quotationItemId: undefined,
			productTypeId: undefined
		}
	]
})
const rules = {
	procureName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
	projectId: [{ required: true, message: '项目不能为空', trigger: 'blur' }]
}
const addItem = () => {
	form.projectProcureItemBos.push({
		itemName: '',
		itemParameter: '',
		itemBrand: '',
		itemNumber: 1,
		itemUnitPrice: 0,
		itemArrivalTime: undefined,
		itemType: undefined,
		quotationItemId: undefined,
		productTypeId: undefined
	})
}

const loading = ref(false)
const list = ref([])
const options = ref([])

selectProject().then((res) => {
	list.value = res.map((e) => {
		return {
			label: e.projectName,
			value: e.projectId
		}
	})
	options.value = list.value
})
const remoteMethod = (query) => {
	if (query) {
		loading.value = true
		setTimeout(() => {
			loading.value = false
			options.value = list.value.filter((item) => {
				return item.label.toLowerCase().includes(query.toLowerCase())
			})
		}, 200)
	} else {
		options.value = list.value
	}
}

const { projectId } = toRefs(form)
const quotationList = ref([])

watch(projectId, () => {
	getQuotation(projectId.value).then((res) => {
		quotationList.value = res.map((e) => {
			return {
				label: e.itemName,
				value: e.itemId + ''
			}
		})
	})
})

const deleteRow = (index) => {
	form.projectProcureItemBos.splice(index, 1)
}
const submit = () => {
	baseform.value.validate((valid, e) => {
		if (valid) {
			updateProcure(form).then((res) => {
				proxy.$modal.msgSuccess('修改成功！')
				tagsView.delView(router.currentRoute.value)
				router.go(-1)
			})
		}
	})
}
const reback = () => {
	tagsView.delView(router.currentRoute.value)
	router.go(-1)
}
</script>
<style lang="scss" scoped>
.header {
	height: 40px;
	line-height: 40px;
	border-bottom: 1px rgba(240, 240, 240, 1) solid;
	margin-bottom: 5px;
}
.item-row {
	width: max-content;
	height: 50px;
	line-height: 50px;
	border-bottom: 1px rgba(240, 240, 240, 1) solid;
	display: flex;
	.item-col {
		width: 200px;
	}
}
</style>
